package com.blockmeta.bbs.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.core.view.GestureDetectorCompat;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import com.blankj.utilcode.util.LogUtils;

import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.R;
import com.blockmeta.bbs.baselibrary.net.callback.Callback;
import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.provider.IMApplicationContextProvider;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.StatusBarUtils;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.gson.GsonUtil;
import com.blockmeta.bbs.baselibrary.utils.richtext.RichText;
import com.blockmeta.bbs.businesslibrary.interfaces.FragmentHolder;
import com.blockmeta.bbs.businesslibrary.interfaces.ITabAction;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.pojo.PushFastNewsPOJO;
import com.blockmeta.bbs.businesslibrary.widget.custom.DrawableRadioButton;
import com.blockmeta.bbs.businesslibrary.widget.custom.MessageRadioButton;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.business.UmengEvent;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.eventbus.IMMsgCountEvent;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.eventbus.XGPushEvent;
import com.blockmeta.bbs.businesslibrary.net.okhttp.OKHttpGetReq;
import com.blockmeta.bbs.businesslibrary.net.pojo.UserToken;
import com.blockmeta.bbs.businesslibrary.pojo.ChainBarMapping;
import com.blockmeta.bbs.businesslibrary.pojo.PushParamsPOJO;
import com.blockmeta.bbs.businesslibrary.pojo.RatePOJO;
import com.blockmeta.bbs.businesslibrary.receiver.ApkInstallReceiver;
import com.blockmeta.bbs.businesslibrary.service.DownloadService;
import com.blockmeta.bbs.businesslibrary.service.MyGTPushService;
import com.blockmeta.bbs.businesslibrary.umeng.ShareRouter;
import com.blockmeta.bbs.businesslibrary.umeng.ShareType;
import com.blockmeta.bbs.businesslibrary.umeng.dialog.BlockMessageShareData;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.DeepLinkUtils;
import com.blockmeta.bbs.businesslibrary.util.DialogUtil;
import com.blockmeta.bbs.businesslibrary.widget.scale.BannerScalePopupWindow;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.minemodule.fragment.MineFragment;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.igexin.sdk.PushManager;
import com.umeng.socialize.UMShareAPI;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * creat by author
 */
@Route(path = RouterPath.MAIN_ACTIVITY)
public class MainActivity extends BaseActivity implements DialogUtil.OnDialogClickListener, PageControlX {

    public View v;
    private FrameLayout mainVp;
    private List<Fragment> fragments = null;
    private RadioGroup rg;
    private MessageRadioButton mMessageRadioButton;
    private DrawableRadioButton mMarketRadioButton;
    private DrawableRadioButton mNewRadioButton;
    private DrawableRadioButton mBBSRadioButton;
    private DrawableRadioButton mMineRadioButton;
    private long mPressedTime;
    private AlertDialog mustUpdateDialog;

    public static ChainBarMapping sChainBarMapping;

    public ApkInstallReceiver apkInstallReceiver = null;

    CountDownTimer timer = new CountDownTimer(3000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            checkUpdate();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
        if (apkInstallReceiver == null) {
            apkInstallReceiver = new ApkInstallReceiver();
            registerReceiver(apkInstallReceiver, new IntentFilter(Constant.DOWN_LOAD_ACTION));
        }

        //IM服务绑定和启动！
        if (AccountHelper.isLogin() && AccountHelper.getUserPhonePOJO() != null) {
            initIMMsgCount();
        } else {
        }

    }

    /**
     * 展示活动
     */
    private void showBannerPopup() {
        final UserToken.FlashBean flashBean;
        PackageInfo mPi = null;
        try {
            flashBean = GsonUtil.buildGson().fromJson(SharedPreferenceUtil.getString(mContext, Constant.BANNER_FLASH, ""), UserToken.FlashBean.class);

        } catch (Exception e) {
            return;
        }
        if (flashBean == null || flashBean.getLink() == null || TextUtils.isEmpty(flashBean.getLink())
                    || flashBean.getImage() == null || TextUtils.isEmpty(flashBean.getImage())) {
            return;
        }
        //times    day每天1次  day-15每天15点后   start每次启动  version新版本
        if (flashBean.getTimes().equals("day")) {//每天启动一次
            String lastTime = SharedPreferenceUtil.getString(mContext, Constant.BANNER_TIME, "1");
            String currentTime = FormatUtil.getTimetoHMS(System.currentTimeMillis(), "yyyyMMdd");
            if (!lastTime.equals(currentTime)) {
                creatBanner(flashBean);
                SharedPreferenceUtil.putString(mContext, Constant.BANNER_TIME, currentTime);
            } else {
                return;
            }
        } else if (flashBean.getTimes().equals("unlimit")) {//每次都启动
            creatBanner(flashBean);
        } else if (flashBean.getTimes().equals("version")) {//新版本
            try {
                mPi = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {

            }
            if (SharedPreferenceUtil.getString(mContext, Constant.APP_VERSION, "").equals(mPi.versionName)) {
                return;
            } else {
                creatBanner(flashBean);
            }

        } else if (isBelong()) {//三点之后启动
            creatBanner(flashBean);
        }


    }

    private void creatBanner(final UserToken.FlashBean flashBean) {
        final BannerScalePopupWindow scalePopupWindow = new BannerScalePopupWindow(MainActivity.this);
        Glide.with(mContext).load(flashBean.getImage()).into(scalePopupWindow.banner);
        scalePopupWindow.banner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                ToastUtil.show("跳转到指定链接" + flashBean.getLink());
                if (!TextUtils.isEmpty(flashBean.getLink())) {
                    String url = DeepLinkUtils.regexUri(flashBean.getLink());
                    DeepLinkUtils.jumpToTarget(mContext, Uri.parse(url));
                }
                UmengEvent.eventStatistics(mContext, Constant.U_ACTIVITY_TOAST, null);
                scalePopupWindow.dismiss();
            }
        });
        scalePopupWindow.showPopupWindow();
    }


    public boolean isBelong() {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
        Date now = null;
        Date beginTime = null;
        Date endTime = null;
        try {
            now = df.parse(df.format(new Date()));
            beginTime = df.parse("15:00");
            endTime = df.parse("24:00");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Boolean flag = belongCalendar(now, beginTime, endTime);
        return flag;
    }


    /**
     * 判断时间是否在时间段内
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        // com.getui.demo.DemoPushService 为第三  定义推送服务,可多次初始化
        PushManager.getInstance().initialize(this.getApplicationContext(), MyGTPushService.class);

        setTitleText("趣会");
        v = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        initData();
        timer.start();
        String pushJson = getIntent().getStringExtra(Constant.PUSH_JSON);
        LogUtils.d("8btcting", "mainactivity" + pushJson);

        if (!TextUtils.isEmpty(pushJson)) {
            //如果推送的消息参数不为空则处理推送跳转
            PushParamsPOJO pushParamsPOJO = new Gson().fromJson(pushJson, PushParamsPOJO.class);
            if (pushParamsPOJO != null && !TextUtils.isEmpty(pushParamsPOJO.deeplink)) {
                LogUtils.d("getuipush", "mainactivity" + pushJson);
                Uri uri = Uri.parse(pushParamsPOJO.deeplink);
                DeepLinkUtils.jumpToTarget(this, uri);
            }
        }
        //上传信鸽token
        uploadXGToken();
        return v;
    }

    /**
     * 上传信鸽token 服务端绑定此token
     */
    private void uploadXGToken() {
        String lastToken = SharedPreferenceUtil.getString(mContext, Constant.TOKEN, "");
        String GETUI_TOKEN = SharedPreferenceUtil.getString(this, Constant.GETUI_TOKEN, null);
        if (GETUI_TOKEN == null) return;
        Map<String, String> map = new HashMap<>();
        map.put("cid", GETUI_TOKEN);
        OkHttpUtils.put()
                .addHeader("from", "android")
                .addHeader("token", lastToken)
                .requestBody(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(map)))
                .url(NetConstant.UPLOAD_XGTOKEN)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {

                    }
                });
    }

    //检查更新
    private void checkUpdate() {
        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        String local = provider.getProjectBuildInfo().version_name;
        String remote = SharedPreferenceUtil.getString(this, Constant.APP_VERSION, "");
        boolean force = SharedPreferenceUtil.getBoolean(this, Constant.ISFORCE, false);
        if (local.compareTo(remote) < 0 && force) {
            showUpdate(force);
        } else if (!SharedPreferenceUtil.getBoolean(this, Constant.NO_NOTICE_UPDATE, false) && local.compareTo(remote) < 0) {
            showUpdate(force);
        } else {
            showBannerPopup();
        }

    }

    private void showUpdate(boolean force) {

        if (force) {//强制更新
            mustUpdateDialog = DialogUtil.showMustUpdate(this, this);
        } else {
            DialogUtil.showUpdate(this, this);
        }
    }

    private int getInt(String a) {
        return Integer.valueOf(a);
    }


    private void initData() {
        mainVp = v.findViewById(R.id.main_vp);
        rg = v.findViewById(R.id.main_rg);
        mMessageRadioButton = v.findViewById(R.id.tab4);
        mMarketRadioButton = v.findViewById(R.id.tab1);
        mNewRadioButton = v.findViewById(R.id.tab2);
        mBBSRadioButton = v.findViewById(R.id.tab3);
        mMineRadioButton = v.findViewById(R.id.tab5);
        mMarketRadioButton.setOnTouchListener(new MyTopTouchListener(this, 0));
        mNewRadioButton.setOnTouchListener(new MyTopTouchListener(this, 1));
        mBBSRadioButton.setOnTouchListener(new MyTopTouchListener(this, 2));
        mMessageRadioButton.setOnTouchListener(new MyTopTouchListener(this, 3));
        mMineRadioButton.setOnTouchListener(new MyTopTouchListener(this, 4));
        initContentFragment();
        initBottom();
    }


    private void initContentFragment() {
        if (TextUtils.isEmpty(SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))) {
            AccountHelper.doLoginOut();
        }
        OKHttpGetReq getReq = new OKHttpGetReq(mContext, NetConstant.ALL_RATE);
        getReq.getDataList(new Callback() {
            @Override
            public void onError(String resp) {

            }

            @Override
            public void onResponse(String resp, int id) {
                try {
                    RatePOJO ratePOJO = GsonUtil.buildGson().fromJson(resp, RatePOJO.class);
                    SharedPreferenceUtil.putFloat(mContext, Constant.CNY_USD, (float) ratePOJO.getRate().getUsd_cny());
                } catch (Exception e) {
                }

            }
        });
        OKHttpGetReq getReq1 = new OKHttpGetReq(mContext, NetConstant.HOT_SEARCH_NET);
        getReq1.getDataList(new Callback() {
            @Override
            public void onError(String resp) {

            }

            @Override
            public void onResponse(String resp, int id) {
                SharedPreferenceUtil.putString(mContext, Constant.HOT_SEARCH_TAGS, resp);
            }
        });

        fragments = new ArrayList<>();
        fragments.add(RouterHelper.fragment(RouterPath.HOME_BASE_FRAGMENT));
        fragments.add(RouterHelper.fragment(RouterPath.NEWS_FRAGMENT));
        fragments.add(RouterHelper.fragment(RouterPath.BBS_BASE_FRAGMENT));
        fragments.add(RouterHelper.fragment(RouterPath.CHAINTHING_FRAGMENT));
        fragments.add(RouterHelper.fragment(RouterPath.ACTIVE_FRAGMENT));
//        fragments.add(mActivityFragment);
//        fragments.add(mActivityFragment);
//        fragments.add(mActivityFragment);
//        fragments.add(mActivityFragment);
        fragments.add(RouterHelper.fragment(RouterPath.IM_HOME_FRAGMENT));
        fragments.add(RouterHelper.fragment(RouterPath.MINE_FRAGMENT));
        switchFragment(0);
    }

    /**
     * 点击底部的切换
     */
    private void initBottom() {

//        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
//                if (i == R.id.tab1) {
//                    switchFragment(0);
//                    UmengEvent.eventStatistics(mContext, Constant.U_COINS, null);
//
//                } else if (i == R.id.tab2) {
//                    switchFragment(1);
//
//                    UmengEvent.eventStatistics(mContext, Constant.U_INFO, null);
//
//
//                } else if (i == R.id.tab3) {
//                    switchFragment(2);
//                    UmengEvent.eventStatistics(mContext, Constant.U_BBS, null);
//
//
//                } else if (i == R.id.tab4) {
//                    switchFragment(3);
//                    UmengEvent.eventStatistics(mContext, Constant.U_ACTIVE, null);
////                    UmengEvent.eventStatistics(mContext, Constant.U_IM, null);
//
//
//                } else if (i == R.id.tab5) {
//                    switchFragment(4);
//                    UmengEvent.eventStatistics(mContext, Constant.U_MINE, null);
//                }
//            }
//
//        });
    }

    /**
     * 切换Fragment
     *
     * @param pos
     */

    private void switchFragment(int pos) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        int length = fragments.size();
        for (int i = 0; i < length; i++) {
            Fragment fragment = fragments.get(i);
            if (i == pos) {

                if(!fragment.isAdded() && null == getSupportFragmentManager().findFragmentByTag(getFragmentTag(pos))){
                    fragmentTransaction.add(R.id.main_vp, fragment, getFragmentTag(pos));
                }else {
                    fragmentTransaction.show(fragment);
                }
                if(fragment.getClass().equals(MineFragment.class)){
                    StatusBarUtils.setWindowStatusBarColor(this, R.color.status_color);
                    StatusBarUtils.setDarkMode(this);
                }else {
                    StatusBarUtils.setWindowStatusBarColor(this, R.color.chainthing_status_color);
                    StatusBarUtils.setLightMode(this);
                }
            } else {
                if (fragment.isAdded()) {
                    fragmentTransaction.hide(fragment);
                }
            }
        }
        try {
            fragmentTransaction.commitAllowingStateLoss();

        } catch (Exception e) {
        }
    }

    @NonNull
    private String getFragmentTag(int pos) {
        return "mainactivityfragment" + pos;
    }

    private void CancleCountDownTimer(int pos) {
//        HomeBaseFragment homeBaseFragment = (HomeBaseFragment) fragments.get(0);
//        if (homeBaseFragment.homeFragment != null && homeBaseFragment.homeFragment.mCountDownTimer != null) {
//            if (pos == 0) {
//                homeBaseFragment.homeFragment.mCountDownTimer.start();
//            } else {
//                homeBaseFragment.homeFragment.mCountDownTimer.cancel();
//            }
//        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //防止Fragment的复用问题
//        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }



    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long nowTime = System.currentTimeMillis();
            if (nowTime - mPressedTime > 2000) {
                ToastUtil.show("再按一次退出");
                mPressedTime = nowTime;
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 下载更新
     *
     * @param url 下载链接
     */
    private void updateApp(String url) {

        ApkInstallReceiver.downloadApkFile(MainActivity.this, new DownloadService.DownloadCallback() {
            Window window;
            ProgressBar mProgressBar;

            @Override
            public void onStart() {
                if (mustUpdateDialog != null) {
                    window = mustUpdateDialog.getWindow();
                    if (window != null) {
                        mProgressBar = window.findViewById(R.id.down_progressbar);
                        mProgressBar.setMax(100);
                    }
                }
            }

            @Override
            public void onProgress(int progress, int totalSize) {
                if (mProgressBar != null) {
                    mProgressBar.setProgress(progress);
                }
            }


            //TODO 这里的 onFinish 和 onInstallAppAndAppOnForeground 会有功能上的重合，后期考虑合并优化。
            @Override
            public boolean onFinish(final File file) {
                return true;
            }

            @Override
            public void onError(String msg) {
            }

            @Override
            public boolean onInstallAppAndAppOnForeground(File file) {
                return true;
            }
        });
    }


    @Override
    public void onDialogClick(int id) {
        String url = SharedPreferenceUtil.getString(this, Constant.UPDATE_URL, null);
        if (url != null) {
            updateApp(url);
        }
    }

    @Subscribe(sticky = true)
    public void XGPush(final XGPushEvent xgPushEvent) {
        new CountDownTimer(500, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                ((RadioButton) (rg.getChildAt(xgPushEvent.pageNo))).setChecked(true);
                switchFragment(xgPushEvent.pageNo);
                if (TextUtils.isEmpty(xgPushEvent.tid)) {
                    return;
                }
                prepareShare(xgPushEvent.tid);
            }
        }.start();
    }

    /**
     * 准备分享快讯的弹窗
     * @param tid 快讯ID
     */
    private void prepareShare(String tid) {
        OKHttpGetReq okHttpGetReq = new OKHttpGetReq(mContext, NetConstant.FAST_DETAIL);
        HashMap<String, String> map = new HashMap<>(2);
        map.put("id", tid);
        okHttpGetReq.getDataWithParam(new Callback() {
            @Override
            public void onError(String resp) {
            }
            @Override
            public void onResponse(String resp, int id) {
                try {
                    Type type = new TypeToken<BaseCodeResponse<PushFastNewsPOJO>>(){}.getType();
                    BaseCodeResponse<PushFastNewsPOJO> data = GsonUtil.buildGson().fromJson(resp,type);
                    PushFastNewsPOJO pojo = data.data;
                    BlockMessageShareData shareData = new BlockMessageShareData();
                    shareData.mTitle = pojo.title;
                    shareData.mPostTime = pojo.postDate;
                    shareData.mImage = pojo.image;
                    shareData.mVerifyName = pojo.authorInfo.displayName;
                    shareData.mSourceImage = pojo.source.ioc;
                    shareData.mSourceName = pojo.source.name;
                    String url = "https://www.8btc.com/article/"+pojo.id;
                    if (pojo.content != null && pojo.content.length() > 0) {
                        Document parse = Jsoup.parse(pojo.content);
                        shareData.mContent = parse.body().text();
                    }
                    new ShareRouter.Builder()
                            .context(mContext)
                            .shareType(ShareType.BLOCk_MESSAGE)
                            .url(url)
                            .thumb(pojo.image)
                            .describe(pojo.desc)
                            .title(pojo.title)
                            .blockMessageShareData(shareData)
                            .build()
                            .show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },map);
    }

    //-----------------------------------------------IM---------------------------------------------------
    //----------------------------------IM初始化模块-----------------------------------------------------------



    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void LoginUI(MsgSuccess message) {
        if (message.msg.equals("LOGIN") && AccountHelper.isLogin() && AccountHelper.getUserPhonePOJO() != null) {
            //登陆成功请求网络数据，Socket连接建立
            //绑定IM 广播和服务
            LogUtils.d("author" + " LoginUI(MsgSuccess message)");
            IMApplicationContextProvider provider = RouterHelper.getProvider(RouterPath.IM_APPLICATIONCONTEXT_PROVIDER);
            if(provider != null){
                provider.onCreate(mContext);
            }
        }else if(message.msg.equals("LOGIN") && !AccountHelper.isLogin()){
            //绑定IM 广播和服务
            LogUtils.d("author" + " LoginUI(loginout message)");
            IMApplicationContextProvider provider = RouterHelper.getProvider(RouterPath.IM_APPLICATIONCONTEXT_PROVIDER);
            if(provider != null){
                provider.onDestroy(mContext);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void IMMsgCount(IMMsgCountEvent imMsgCountEvent){
        mMessageRadioButton.setMessageCount(imMsgCountEvent.getMsgCount());
    }

    private void initIMMsgCount(){
        int unCheckedCount = IMApplicationContext.getChatMessageDomainService().getUnCheckedMsgCount(AccountHelper.getUidInt());
        mMessageRadioButton.setMessageCount(unCheckedCount);
    }
    @Override
    protected void onDestroy() {
        //释放资源
        UMShareAPI.get(this).release();
        timer.cancel();
        if (apkInstallReceiver != null) {
            unregisterReceiver(apkInstallReceiver);
            apkInstallReceiver = null;
        }
        EventBus.getDefault().unregister(this);
        RichText.recycle();
        super.onDestroy();
    }

    @Override
    public int getCurrentItem() {
        View view = rg.findViewById(rg.getCheckedRadioButtonId());
        int index = rg.indexOfChild(view);
        if(index != -1){
            return index;
        }else {
            return 0;
        }
    }

    @Override
    public void setCurrentItem(int currentFixIndex) {

        View childAt = rg.getChildAt(currentFixIndex);
        if(childAt instanceof DrawableRadioButton){
            DrawableRadioButton radioButton = (DrawableRadioButton)childAt;
            if (radioButton.isNeedLogin&&radioButton.toLoginIfUnLogin()){
                return;
            }
            ((DrawableRadioButton)childAt).setChecked(true);
        }else {
            Log.d("tapup", "not DrawableRadioButton");
        }
        switchFragment(currentFixIndex);
    }

    @Override
    public Object getItem(int position) {
        return fragments.get(position);
    }


    public class MyTopTouchListener implements View.OnTouchListener {
        private final int index;
        private PageControlX pageControl;


        public MyTopTouchListener(PageControlX pageControl, int index) {
            this.pageControl = pageControl;
            this.index = index;
        }
        GestureDetectorCompat detector = new GestureDetectorCompat(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
//@返回TRUE如果事件被消耗，否则假
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (pageControl.getCurrentItem() != index) {
                    pageControl.setCurrentItem(index);
                    return true;
                } else {
                    Object fragment = pageControl.getItem(index);
                    Log.d("tapup", fragment.toString());
                    if (fragment instanceof ITabAction) {
                        ((ITabAction) fragment).tabClickToRefreshList();
                    } else if (fragment instanceof FragmentHolder) {
                        ITabAction finalFragmentByFragmentHolder = findFinalFragmentByFragmentHolder(((FragmentHolder) fragment));
                        if (finalFragmentByFragmentHolder != null) {
                            finalFragmentByFragmentHolder.tabClickToRefreshList();
                        }
                    }
                    return false;
                }
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
//                int current = index;
//                //Prt.d(TAG, "onDoubleTap");
//                Object fragment = pageControl.getItem(current);
//                Log.d("tapup", "double tap" + fragment.toString());
//                if (fragment instanceof ITabAction) {
//                    ((ITabAction) fragment).tabClickToRefreshList();
//                } else if (fragment instanceof FragmentHolder) {
//                    ITabAction tabActonX = findFinalFragmentByFragmentHolder(((FragmentHolder) fragment));
//                    if (tabActonX != null) {
//                        tabActonX.tabClickToRefreshList();
//                    }
//                }

                return super.onDoubleTap(e);
            }
        });

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            detector.onTouchEvent(event);
            return true;
        }
    }

    public ITabAction findFinalFragmentByFragmentHolder(FragmentHolder fragment) {
        Object currentFragment = fragment.getCurrentFragment();
        if (currentFragment == null){
            return null;
        }
        if (currentFragment instanceof ITabAction) {
            return (ITabAction) currentFragment;
        } else if (currentFragment instanceof FragmentHolder) {
            return findFinalFragmentByFragmentHolder((FragmentHolder) currentFragment);
        } else {
            return null;
        }
    }
}
